#include "cluster_project.h"

#define DLL

#ifdef DLL
int __declspec(dllexport) mainFunc(double precision, int uid, long timestamp)
#else
int main(int argc, char **argv)
#endif
{
	FILE *fp;
	int iMatrixSize;
	sparse_matrix_lst *A;
	elem deltaQ, deltaDeltaQ;
	LINK divisibleGroups;/*All the groups which we can still divide*/
	LINK undivisibleGroups;/*The undivisible groups - wating to be printed*/
	int numOfGroups = 0;

	/*generate A_sparse*/
#ifdef DLL
	char in_path[256], out_path[256];
	sprintf(in_path,"C:\\IN\\%d.in",uid);
	sprintf(out_path,"C:\\OUT\\%d-%d.out",uid,timestamp);

	if (createSparseMatrixFromFile(in_path,&A,&iMatrixSize) == 0)
	{
		return 0;
	}
#else
	double precision = atof(argv[2]);

	/*generate A_sparse*/
	if (createSparseMatrixFromFile(argv[1],&A,&iMatrixSize) == 0)
	{
		return 0;
	}
#endif

	/*First we start with the trivial division marked as divisible*/
	if (createTheTrivialDivision(&divisibleGroups, A->n) == 0)
	{
		free_sparse_matrix_lst(A);
		return 0;
	}

	undivisibleGroups = NULL;
	deltaQ = 0;
	
	/*Steps 3 to 19 in Algorithm 3*/
	while (!isEmpty(divisibleGroups))
	{
		if (oneAlogrithm3Itteration(A, &divisibleGroups, &undivisibleGroups, precision, &numOfGroups, &deltaDeltaQ) == 0)
		{
			free_sparse_matrix_lst(A);
			deleteList(&divisibleGroups);
			deleteList(&undivisibleGroups);
			return 0;
		}
		deltaQ += deltaDeltaQ;
	}

	fp = fopen(out_path, "w");
	if (fp == NULL)
	{
		printf("ERROR opening output file\n");
		return 0;
	}
	fprintf(fp,"%f\n", deltaQ);
	fprintf(fp,"%d\n", numOfGroups);
	fclose(fp);

#ifdef DLL
	printList(undivisibleGroups, numOfGroups, deltaQ, out_path);
#else
	printList(undivisibleGroups, numOfGroups, "C:\\OUT\1111.out");
#endif

	free_sparse_matrix_lst(A);
	deleteList(&divisibleGroups);
	deleteList(&undivisibleGroups);	

	return 777;
}
